export class ViewDrag {

    public ui: fgui.GObject;

    private _isPressed: boolean;
    private _cacheId: number;
    private _cachePos: Laya.Vector2;

    public onDrag: Laya.Handler;

    constructor(ui: fgui.GObject) {
        this.ui = ui;
        this._isPressed = false;
        this._cachePos = new Laya.Vector2(0, 0);
        this.ui.on(Laya.Event.MOUSE_DOWN, this, this._OnMouseDown);
        Laya.stage.on(Laya.Event.MOUSE_MOVE, this, this._OnMouseMove);
        Laya.stage.on(Laya.Event.MOUSE_UP, this, this._OnMouseUp);
    }

    public Dispose() {
        this.ui.off(Laya.Event.MOUSE_DOWN, this, this._OnMouseDown);
        Laya.stage.off(Laya.Event.MOUSE_MOVE, this, this._OnMouseMove);
        Laya.stage.off(Laya.Event.MOUSE_UP, this, this._OnMouseUp);
        if (this.onDrag != null) {
            this.onDrag.recover();
            this.onDrag = null;
        }
    }

    private _OnMouseDown(event: Laya.Event) {
        if (this._isPressed) return;
        this._isPressed = true;
        this._cacheId = event.touchId;
        this._cachePos.x = event.stageX;
        this._cachePos.y = event.stageY;
    }

    private _OnMouseMove(event: Laya.Event) {
        if (!this._isPressed) return;
        if (event.touchId != this._cacheId) return;
        this.onDrag?.runWith([event.stageX - this._cachePos.x, event.stageY - this._cachePos.y]);
        this._cachePos.x = event.stageX;
        this._cachePos.y = event.stageY;
    }

    private _OnMouseUp(event: Laya.Event) {
        if (!this._isPressed) return;
        if (event.touchId != this._cacheId) return;
        this._isPressed = false;
        this._cacheId = null;
    }

}